package com.sub.framework.rabbitmq;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sub.project.rabbit.KnowledgeInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;


/**
 *  确认消费模式 - 生产者
 */
//@Component
public class KnowledgePublisher {
    private  static final Logger log =  LoggerFactory.getLogger(KnowledgePublisher.class);

    /** JSON 序列化和反序列化*/
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /** 定义环境变量读取*/
    @Autowired
    private Environment environment;

    public void sendMsg(KnowledgeInfo message){
        if (message != null) {
            try {
                /*定义消息传输的格式*/
                rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
                // 设置交换机
                rabbitTemplate.setExchange(environment.getProperty("mq.auto.knowledge.exchange.name"));
                //设置路由
                rabbitTemplate.setRoutingKey(environment.getProperty("mq.auto.knowledge.routing.key.name"));

                Message msg = MessageBuilder.withBody(objectMapper.writeValueAsBytes(message))
                        .setDeliveryMode(MessageDeliveryMode.PERSISTENT)
                        .build();

                rabbitTemplate.convertAndSend(msg);
                System.out.println("基于AUTO机制消息模型-生产者-发送消息："+message);
                log.info("基于AUTO机制消息模型-生产者-发送消息：{}",message);

            }catch (Exception e){
                log.info("基于AUTO机制消息模型-生产者-发送消息异常：{}",message,e.fillInStackTrace());
            }
        }
    }
}
